import { apiClient } from './apiClient'
import { ApiResponse } from '@/types/api'

export interface ExecuteRequest {
  connection_id: string
  sql: string
  limit?: number
  timeout?: number
  auto_commit?: boolean
  explain_only?: boolean
}

export interface ExecuteResponse {
  query_id: string
  columns: Array<{
    name: string
    type: string
    nullable?: boolean
  }>
  rows: any[][]
  total_rows: number
  affected_rows?: number
  execution_time: number
  explain_plan?: string
}

export interface ExecutionHistoryParams {
  connection_id?: string
  status?: 'completed' | 'failed' | 'cancelled'
  start_date?: string
  end_date?: string
  limit?: number
  offset?: number
}

export interface ExecutionHistoryResponse {
  executions: Array<{
    id: string
    sql: string
    connection_name: string
    connection_id: string
    status: 'completed' | 'failed' | 'cancelled'
    start_time: string
    end_time?: string
    duration: number
    rows_affected?: number
    rows_returned?: number
    error_message?: string
    created_by: string
  }>
  total: number
}

/**
 * 执行SQL查询
 */
export const executeSQL = async (request: ExecuteRequest): Promise<ApiResponse<ExecuteResponse>> => {
  const response = await apiClient.post('/api/executions/execute', request)
  return response.data
}

/**
 * 取消SQL执行
 */
export const cancelExecution = async (executionId: string): Promise<ApiResponse<void>> => {
  const response = await apiClient.post(`/api/executions/${executionId}/cancel`)
  return response.data
}

/**
 * 获取执行状态
 */
export const getExecutionStatus = async (executionId: string): Promise<ApiResponse<{
  id: string
  status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled'
  progress?: number
  message?: string
  start_time?: string
  end_time?: string
  duration?: number
  error?: string
}>> => {
  const response = await apiClient.get(`/api/executions/${executionId}/status`)
  return response.data
}

/**
 * 获取执行结果
 */
export const getExecutionResult = async (executionId: string): Promise<ApiResponse<ExecuteResponse>> => {
  const response = await apiClient.get(`/api/executions/${executionId}/result`)
  return response.data
}

/**
 * 获取执行历史
 */
export const getExecutionHistory = async (params?: ExecutionHistoryParams): Promise<ApiResponse<ExecutionHistoryResponse>> => {
  const response = await apiClient.get('/api/executions/history', { params })
  return response.data
}

/**
 * 删除执行历史记录
 */
export const deleteExecutionHistory = async (executionId: string): Promise<ApiResponse<void>> => {
  const response = await apiClient.delete(`/api/executions/history/${executionId}`)
  return response.data
}

/**
 * 清空执行历史
 */
export const clearExecutionHistory = async (): Promise<ApiResponse<void>> => {
  const response = await apiClient.delete('/api/executions/history')
  return response.data
}

/**
 * 导出执行结果
 */
export const exportExecutionResult = async (
  executionId: string, 
  format: 'csv' | 'excel' | 'json'
): Promise<Blob> => {
  const response = await apiClient.get(`/api/executions/${executionId}/export`, {
    params: { format },
    responseType: 'blob',
  })
  return response.data
}

/**
 * 获取查询解释计划
 */
export const getQueryExplain = async (request: {
  connection_id: string
  sql: string
}): Promise<ApiResponse<{
  explain_plan: string
  estimated_cost?: number
  estimated_rows?: number
}>> => {
  const response = await apiClient.post('/api/executions/explain', request)
  return response.data
}

/**
 * 获取执行统计
 */
export const getExecutionStats = async (params?: {
  connection_id?: string
  start_date?: string
  end_date?: string
}): Promise<ApiResponse<{
  total_executions: number
  successful_executions: number
  failed_executions: number
  average_duration: number
  total_duration: number
  most_used_connections: Array<{
    connection_id: string
    connection_name: string
    count: number
  }>
  execution_trends: Array<{
    date: string
    count: number
    avg_duration: number
  }>
}>> => {
  const response = await apiClient.get('/api/executions/stats', { params })
  return response.data
}